package com.wangxianseng.file;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wangxianseng.bean.ConfigProp;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class FileUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();
    public static List<File> getAllFiles(File folder) {
        List<File> fileList = new ArrayList<>();

        // 检查文件夹是否存在且确实为一个文件夹
        if (folder.exists() && folder.isDirectory()) {
            // 列出文件夹中所有的文件和子文件夹
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        // 如果是文件，则添加到列表中
                        fileList.add(file);
                    } else if (file.isDirectory()) {
                        // 如果是文件夹，则递归调用该方法
                        fileList.addAll(getAllFiles(file));
                    }
                }
            }
        }
        return fileList;
    }

    public static List<ConfigProp> getFindValueListByFile(String dependencyFilePath) {
        List<ConfigProp> findValueList = new LinkedList<>();
        File file = new File(dependencyFilePath);
        if (!file.isFile()) {
            return findValueList;
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if ("".equals(line)||line.startsWith("#")) continue;

                JsonNode jsonNode = null;
                try {
                    jsonNode = objectMapper.readTree(line);
                } catch (JsonProcessingException e) {
                    log.error("本行配置有误 【{}】",line);
                    e.printStackTrace();
                }
                ConfigProp findValue = objectMapper.convertValue(jsonNode, ConfigProp.class);
                findValueList.add(findValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return findValueList;
    }
}
